package com.tqw.order.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.tqw.constant.SecurityConstants;
import com.tqw.entity.JWTUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author: czm
 * @Date: 2022/04/19/9:21
 * @Description:
 */
@Component
public class TqwMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private HttpServletRequest request;

    //自动填充时间
    @Override
    public void insertFill(MetaObject metaObject) {
        String token = request.getHeader(SecurityConstants.AUTH_TOKEN);
        Integer clientId = 1;
        if(token!=null){
            clientId = JWTUtil.getId(token);
        }
        Date date = new Date();
        this.setFieldValByName("createdTime", date, metaObject);
        this.setFieldValByName("updatedTime", date, metaObject);
        this.setFieldValByName("createBy", clientId, metaObject);
        this.setFieldValByName("updateBy", clientId, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String token = request.getHeader(SecurityConstants.AUTH_TOKEN);
        Integer clientId = 1;
        if(token!=null){
            clientId = JWTUtil.getId(token);
        }
        this.setFieldValByName("updatedTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", clientId, metaObject);
    }
}
